import React, { useRef } from "react";
import {ProTable, ActionType } from "@ant-design/pro-components";
import { Badge, Button, message, Popconfirm, Space, Tag } from "antd";
import Detail from "./component/Detail";
import { useRequest } from "ahooks";
import { articleV1AdminControllerIndex, articleV1AdminControllerUpdate } from "@/services/auto/articleAdmin";
import {
  ArticleCategory,
  ArticleNormalCategory,
  ArticleStatus,
} from "common/utils/data";
import { completeImgUrl, getRichTextArticleTitleCategoryPrefix } from "common/utils/utils";
import { green, orange, blue } from '@ant-design/colors';
import { VerticalAlignTopOutlined } from "@ant-design/icons";
import { Radio } from "antd";

export default function ArticleRichText(){
  const actionRef = useRef<ActionType>();

  const {runAsync: patchRun} = useRequest(articleV1AdminControllerUpdate,{
    manual: true,
    onSuccess: ()=>{
      actionRef.current?.reload();
      message.success('操作成功');
    }
  })

  return <ProTable<API.ArticleAdminIndexResult, API.ArticleV1AdminControllerIndexParams>
    actionRef={actionRef}
    rowKey="uuid"
    options={false}
    pagination={{
      showSizeChanger: true,
      showTotal: (total: number, [start, end]: [number, number]) =>
        `第 ${start}-${end} 条/总共 ${total} 条`,
    }}
    toolBarRender={() => []}
    request={(param) => {
      const { pageSize,current, title, status } = param;
      return articleV1AdminControllerIndex({
        title,
        status,
        pageSize,
        pageIndex: current,
      }).then((res) => {
        return {
          success: true,
          data: res.list,
          total: res.total
        };
      });
    }}
    columns={[
      {
        align: 'center',
        title: '缩略图',
        dataIndex: 'thumbnail',
        width: 120,
        render: (_, record) => {
          return record.thumbnails?.length ? (
            <a
              href={completeImgUrl(record.thumbnails[0])}
              target="_blank"
              className="flex justify-center"
            >
              <img src={completeImgUrl(record.thumbnails[0])} alt="图片" className="w-full" />
            </a>
          ) : '--';
        },
        hideInSearch: true,
      },
      {
        align: 'center',
        title: '标题',
        dataIndex: 'title',
        render: (val, record) => {
          return (
            <Badge
              count={
                <Popconfirm
                  title={record.isStick ? '取消当前置顶吗？' : '确认当前置顶吗？'}
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => {
                    patchRun(
                      {uuid: record.uuid},
                      { isStick: record.isStick === 1 ? 0 : 1 },
                    );
                  }}
                >
                  <VerticalAlignTopOutlined
                    style={{
                      color: record.isStick ? blue.primary : 'initial',
                      fontSize: '18px',
                      cursor: 'pointer',
                    }}
                    title={record.isStick ? '置顶中' : '未置顶'}
                  />
                </Popconfirm>
              }
            >
              {getRichTextArticleTitleCategoryPrefix(record.category as ArticleNormalCategory)} {val}
            </Badge>
          );
        },
      },
      {
        align: 'center',
        title: '状态',
        dataIndex: 'status',
        render: (val) => {
          return (
            <Tag
              color={val === ArticleStatus.PUBLISH ? green.primary : orange.primary}
            >
              {val === ArticleStatus.PUBLISH ? '已发布' : '待审核'}
            </Tag>
          );
        },
        initialValue: ArticleStatus.REVIEW,
        renderFormItem: () => {
          return (
            <Radio.Group
              buttonStyle="solid"
            >
              <Radio.Button value="">全部</Radio.Button>
              <Radio.Button value={ArticleStatus.REVIEW}>待审核</Radio.Button>
              <Radio.Button value={ArticleStatus.PUBLISH}>已发布</Radio.Button>
            </Radio.Group>
          );
        },
      },
      {
        align: 'center',
        title: 'Tag',
        key: 'categoryName',
        hideInSearch: true,
        renderText: (_, record) => {
          return record.categories.map(it=>{
            return getRichTextArticleTitleCategoryPrefix(it as ArticleNormalCategory)
          }).join('');
        },
      },
      {
        align: 'center',
        title: '作者用户',
        key: 'user',
        hideInSearch: true,
        renderText: (val, record)=>{
          return `${record.user.name}（${record.user.mobile}）`
        },
      },
      {
        align: 'center',
        title: '关键词',
        dataIndex: 'keywords',
        hideInSearch: true,
        render: (val) => {
          return (val as string[]).map((item, index) => <Tag key={index}>{item}</Tag>);
        },
      },
      {
        align: 'center',
        title: '最新发布时间',
        dataIndex: 'publishTime',
        hideInSearch: true,
        valueType: 'dateTime',
      },
      {
        align: 'center',
        title: '描述',
        dataIndex: 'desc',
        hideInSearch: true,
        ellipsis: true,
      },
      {
        align: 'center',
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        width: 80,
        render: (_, record) => (
          <Space direction="vertical" size={0}>
            <Detail data={record} reload={actionRef.current?.reload}>
              <Button type="link">详情</Button>
            </Detail>
            {/*<Button
              type="link"
              onClick={() => {
                window.open(history.createHref({
                  pathname: '/carousel',
                  search: `?articleUuid=${record.uuid}`,
                }));
              }}
            >
              设置为轮播
            </Button>*/}
          </Space>
        ),
      },
    ]}
  />
}
